package com.sxbbc.agent.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.sxbbc.agent.service.AgentDataService;
import com.sxbbc.common.basics.enums.LoginChannelEnums;
import com.sxbbc.common.basics.exceptions.ThrowJsonException;
import com.sxbbc.common.basics.utils.calculation.CalcuUtils;
import com.sxbbc.common.basics.utils.statics.StaticUtils;
import com.sxbbc.common.core.dto.jz.CustomerTeamVo;
import com.sxbbc.common.core.entity.jz.*;
import com.sxbbc.common.core.enums.AgentLevelEnums;
import com.sxbbc.common.core.enums.BusinessScopeEnums;
import com.sxbbc.common.core.enums.HandleTypeEnums;
import com.sxbbc.common.core.mapper.jz.BBusinessMapper;
import com.sxbbc.common.core.mapper.jz.CCustomerAuthenMapper;
import com.sxbbc.common.core.mapper.jz.CCustomerMapper;
import com.sxbbc.common.core.mapper.jz.OrderMainMapper;
import com.sxbbc.common.core.service.*;
import com.sxbbc.common.core.utils.BasePage;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.servlet.ModelAndView;

import java.math.BigDecimal;
import java.util.HashSet;
import java.util.Set;

/**
 * 代理 查看数据 实现类
 *
 * @author leehao
 * @date 2019-07-10
 */
@Service
public class AgentDataServiceImpl implements AgentDataService {

    @Autowired
    private IAgAgentService iAgAgentService;
    @Autowired
    private ICCustomerService icCustomerService;
    @Autowired
    private ICustomerLevelInfoService customerLevelInfoService;
    @Autowired
    private BBusinessService bBusinessService;
    @Autowired
    private IAgDonateDetailService iAgDonateDetailService;
    @Autowired
    private IAgAccountService iAgAccountService;
    @Autowired
    private CCustomerAuthenMapper cCustomerAuthenMapper;
    @Autowired
    private BBusinessMapper bBusinessMapper;
    @Autowired
    private IAddressService iAddressService;
    @Autowired
    private IIndustryService iIndustryService;
    @Autowired
    private OrderMainMapper orderMainMapper;
    @Autowired
    private CCustomerMapper cCustomerMapper;

    @Override
    public IPage<CCustomer> queryCustomerList(BasePage<CCustomer> page, AgAgent agent, CCustomer customer) {
        CalcuUtils calUtil = CalcuUtils.getInstance();
        AgAgent agAgent = iAgAgentService.getById(agent.getId());
        if (agAgent == null) {
            throw new ThrowJsonException("获取代理信息失败");
        }
        Set<Integer> cidSet = new HashSet<>();
        if (calUtil.isEquals(agAgent.getLevel(), AgentLevelEnums.PROVINCE_AGENT.getId())) {
            cidSet = cCustomerAuthenMapper.queryCustomerByLocation(agAgent.getProId(), AgentLevelEnums.PROVINCE_AGENT.getId());
        } else if (calUtil.isEquals(agAgent.getLevel(), AgentLevelEnums.CITY_AGENT.getId())) {
            cidSet = cCustomerAuthenMapper.queryCustomerByLocation(agAgent.getCityId(), AgentLevelEnums.CITY_AGENT.getId());
        } else if (calUtil.isEquals(agAgent.getLevel(), AgentLevelEnums.AREA_AGENT.getId())) {
            cidSet = cCustomerAuthenMapper.queryCustomerByLocation(agAgent.getAreaId(), AgentLevelEnums.AREA_AGENT.getId());
        }
        QueryWrapper<CCustomer> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(customer.getNickName())) {
            wrapper.eq("nick_name", customer.getNickName());
        } else if (StringUtils.isNotBlank(customer.getPhone())) {
            wrapper.eq("phone", customer.getPhone());
        } else if (StringUtils.isNotBlank(customer.getQueryTime())) {
            String[] times = customer.getQueryTime().split("~");
            wrapper.apply(true, "date_format(createtime,'%Y-%m-%d') >= {0}", times[0].trim());
            wrapper.apply(true, "date_format(createtime,'%Y-%m-%d') <= {0}", times[1].trim());
        } else if (customer.getLevelid() != null) {
            wrapper.eq("levelid", customer.getLevelid());
        } else if (!CollectionUtils.isEmpty(cidSet)) {
            wrapper.in("id", cidSet);
        } else if (CollectionUtils.isEmpty(cidSet)) {
            wrapper.isNull("id");
        }
        icCustomerService.page(page, wrapper);
        for (CCustomer c : page.getRecords()) {
            c.setPassWord(null);
            c.setPayWord(null);
            c.setOpenidProgram(null);
            c.setChannelName(LoginChannelEnums.getName(c.getRegisterChannel()));
            CustomerLevelInfo levelInfo = customerLevelInfoService.getById(c.getLevelid());
            if (levelInfo != null) {
                c.setLevelName(levelInfo.getName());
            }
            CCustomer parentCustomer = icCustomerService.getById(c.getParentid());
            if (parentCustomer != null) {
                c.setParentName(parentCustomer.getNickName());
            }
            CustomerTeamVo team = new CustomerTeamVo();
            team.setNowLayer(c.getLayer());
            team.setCid(c.getId());
            team.setRecommedLayer(1);
            // 直推
            int direct = cCustomerMapper.countMyTeamNum(team);
            // 间推
            team.setRecommedLayer(2);
            int indirect = cCustomerMapper.countMyTeamNum(team);
            c.setDirectNum(direct);
            c.setIndirectNum(indirect);
        }
        return page;
    }

    @Override
    public IPage<BBusiness> queryBusinessList(BasePage<BBusiness> page, AgAgent agent, BBusiness business) {
        CalcuUtils calUtil = CalcuUtils.getInstance();
        AgAgent agAgent = iAgAgentService.getById(agent.getId());
        if (agAgent == null) {
            throw new ThrowJsonException("获取代理信息失败");
        }
        Set<Integer> bidSet = new HashSet<>();
        if (calUtil.isEquals(agAgent.getLevel(), AgentLevelEnums.PROVINCE_AGENT.getId())) {
            bidSet = bBusinessMapper.queryBusinessByLocation(agAgent.getProId(), AgentLevelEnums.PROVINCE_AGENT.getId());
        } else if (calUtil.isEquals(agAgent.getLevel(), AgentLevelEnums.CITY_AGENT.getId())) {
            bidSet = bBusinessMapper.queryBusinessByLocation(agAgent.getCityId(), AgentLevelEnums.CITY_AGENT.getId());
        } else if (calUtil.isEquals(agAgent.getLevel(), AgentLevelEnums.AREA_AGENT.getId())) {
            bidSet = bBusinessMapper.queryBusinessByLocation(agAgent.getAreaId(), AgentLevelEnums.AREA_AGENT.getId());
        }
        QueryWrapper<BBusiness> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(business.getNickNameOn())) {
            wrapper.eq("nick_name_on", business.getNickNameOn());
        } else if (StringUtils.isNotBlank(business.getNickName())) {
            wrapper.eq("nick_name", business.getNickName());
        } else if (StringUtils.isNotBlank(business.getLicenseCode())) {
            wrapper.eq("license_code", business.getLicenseCode());
        } else if (business.getOpen() != null) {
            wrapper.eq("open", business.getOpen());
        } else if (StringUtils.isNotBlank(business.getLinkPhone())) {
            wrapper.eq("link_phone", business.getLinkPhone());
        } else if (business.getIndustryId() != null) {
            wrapper.eq("industry_id", business.getIndustryId());
        } else if (!CollectionUtils.isEmpty(bidSet)) {
            wrapper.in("id", bidSet);
        } else if (CollectionUtils.isEmpty(bidSet)) {
            wrapper.isNull("id");
        }
        bBusinessService.page(page, wrapper);
        for (BBusiness b : page.getRecords()) {
            b.setPayWord(null);
            b.setAddressDetail(iAddressService.getAddrName(b.getProId(), b.getCityId(), b.getAreaId()) + b.getAddressDetail());
            Industry industry = iIndustryService.getById(b.getIndustryId());
            if (industry != null) {
                b.setIndustryName(industry.getName());
            }
        }
        return page;
    }

    @Override
    public IPage<AgDonateDetail> queryProfitList(BasePage<AgDonateDetail> page, AgAgent agent, AgDonateDetail agDonateDetail) {
        CalcuUtils calc = CalcuUtils.getInstance();
        AgAgent agAgent = iAgAgentService.getById(agent.getId());
        if (agAgent == null) {
            throw new ThrowJsonException("获取代理信息失败");
        }
        QueryWrapper<AgDonateDetail> wrapper = new QueryWrapper<>();
        wrapper.eq("agid", agAgent.getId());
        wrapper.eq("isout", StaticUtils.PAY_IN);
        if (StringUtils.isNotBlank(agDonateDetail.getPayCode())) {
            wrapper.eq("pay_code", agDonateDetail.getPayCode());
        } else if (agDonateDetail.getTypeId() != null) {
            wrapper.eq("target_id", agDonateDetail.getTypeId());
        } else if (StringUtils.isNotBlank(agDonateDetail.getQueryTime())) {
            String[] times = agDonateDetail.getQueryTime().split("~");
            wrapper.apply(true, "date_format(create_time,'%Y-%m-%d') >= {0}", times[0].trim());
            wrapper.apply(true, "date_format(create_time,'%Y-%m-%d') <= {0}", times[1].trim());
        }
        wrapper.orderByDesc("id");
        iAgDonateDetailService.page(page, wrapper);
        for (AgDonateDetail d : page.getRecords()) {
            d.setTypeName(HandleTypeEnums.getName(d.getTypeId()));
            if (calc.isEquals(d.getTypeId(), HandleTypeEnums.AGENT_REWARD.getId())) {
                //商家信息
                BBusiness business = bBusinessService.getById(d.getTargetId());
                if (business == null) {
                    d.setTargetName("");
                }
                if (calc.isEquals(business.getOnOff(), BusinessScopeEnums.ONLINE.getId())) {
                    d.setTargetName(business.getNickNameOn());
                } else if (calc.isEquals(business.getOnOff(), BusinessScopeEnums.OFFLINE.getId())) {
                    d.setTargetName(business.getNickName());
                }
            }
        }
        return page;
    }

    @Override
    public BigDecimal getAgentDonate(AgAgent agent) {
        AgAgent agAgent = iAgAgentService.getById(agent.getId());
        if (agAgent == null) {
            throw new ThrowJsonException("获取代理信息失败");
        }
        AgAccount agAccount = iAgAccountService.selectByAgid(agAgent.getId());
        return agAccount.getDonate();
    }

    /**
     * 统计首页数据
     *
     * @param agAgent
     * @param view
     */
    @Override
    public void queryStatisticalDataByLocation(AgAgent agAgent, ModelAndView view) {
        CalcuUtils calUtil = CalcuUtils.getInstance();
        int todayCustomerNumByLocation = 0;
        int todayBusinessNumByLocation = 0;
        int customerNumByLocation = 0;
        int businessNumByLocation = 0;
        //区域会员总数
        if (calUtil.isEquals(agAgent.getLevel(), AgentLevelEnums.PROVINCE_AGENT.getId())) {
            customerNumByLocation = cCustomerAuthenMapper.queryCustomerNumByLocation(agAgent.getProId(), AgentLevelEnums.PROVINCE_AGENT.getId(), null);
        } else if (calUtil.isEquals(agAgent.getLevel(), AgentLevelEnums.CITY_AGENT.getId())) {
            customerNumByLocation = cCustomerAuthenMapper.queryCustomerNumByLocation(agAgent.getCityId(), AgentLevelEnums.CITY_AGENT.getId(), null);
        } else if (calUtil.isEquals(agAgent.getLevel(), AgentLevelEnums.AREA_AGENT.getId())) {
            customerNumByLocation = cCustomerAuthenMapper.queryCustomerNumByLocation(agAgent.getAreaId(), AgentLevelEnums.AREA_AGENT.getId(), null);
        }
        view.addObject("customerNumByLocation", customerNumByLocation);

        //区域商家总数
        if (calUtil.isEquals(agAgent.getLevel(), AgentLevelEnums.PROVINCE_AGENT.getId())) {
            businessNumByLocation = bBusinessMapper.queryBusinessNumByLocation(agAgent.getProId(), AgentLevelEnums.PROVINCE_AGENT.getId(), null);
        } else if (calUtil.isEquals(agAgent.getLevel(), AgentLevelEnums.CITY_AGENT.getId())) {
            businessNumByLocation = bBusinessMapper.queryBusinessNumByLocation(agAgent.getCityId(), AgentLevelEnums.CITY_AGENT.getId(), null);
        } else if (calUtil.isEquals(agAgent.getLevel(), AgentLevelEnums.AREA_AGENT.getId())) {
            businessNumByLocation = bBusinessMapper.queryBusinessNumByLocation(agAgent.getAreaId(), AgentLevelEnums.AREA_AGENT.getId(), null);
        }
        view.addObject("businessNumByLocation", businessNumByLocation);

        //当天新增会员总数
        if (calUtil.isEquals(agAgent.getLevel(), AgentLevelEnums.PROVINCE_AGENT.getId())) {
            todayCustomerNumByLocation = cCustomerAuthenMapper.queryCustomerNumByLocation(agAgent.getProId(), AgentLevelEnums.PROVINCE_AGENT.getId(), StaticUtils.DAY_DATA);
        } else if (calUtil.isEquals(agAgent.getLevel(), AgentLevelEnums.CITY_AGENT.getId())) {
            todayCustomerNumByLocation = cCustomerAuthenMapper.queryCustomerNumByLocation(agAgent.getCityId(), AgentLevelEnums.CITY_AGENT.getId(), StaticUtils.DAY_DATA);
        } else if (calUtil.isEquals(agAgent.getLevel(), AgentLevelEnums.AREA_AGENT.getId())) {
            todayCustomerNumByLocation = cCustomerAuthenMapper.queryCustomerNumByLocation(agAgent.getAreaId(), AgentLevelEnums.AREA_AGENT.getId(), StaticUtils.DAY_DATA);
        }
        view.addObject("todayCustomerNumByLocation", todayCustomerNumByLocation);

        //当天新增商家总数
        if (calUtil.isEquals(agAgent.getLevel(), AgentLevelEnums.PROVINCE_AGENT.getId())) {
            todayBusinessNumByLocation = bBusinessMapper.queryBusinessNumByLocation(agAgent.getProId(), AgentLevelEnums.PROVINCE_AGENT.getId(), StaticUtils.DAY_DATA);
        } else if (calUtil.isEquals(agAgent.getLevel(), AgentLevelEnums.CITY_AGENT.getId())) {
            todayBusinessNumByLocation = bBusinessMapper.queryBusinessNumByLocation(agAgent.getCityId(), AgentLevelEnums.CITY_AGENT.getId(), StaticUtils.DAY_DATA);
        } else if (calUtil.isEquals(agAgent.getLevel(), AgentLevelEnums.AREA_AGENT.getId())) {
            todayBusinessNumByLocation = bBusinessMapper.queryBusinessNumByLocation(agAgent.getAreaId(), AgentLevelEnums.AREA_AGENT.getId(), StaticUtils.DAY_DATA);
        }
        view.addObject("todayBusinessNumByLocation", todayBusinessNumByLocation);

        //区域商家的订单总数
        Set<Integer> bidList = null;
        if (calUtil.isEquals(agAgent.getLevel(), AgentLevelEnums.PROVINCE_AGENT.getId())) {
            bidList = bBusinessMapper.queryBusinessByLocation(agAgent.getProId(), AgentLevelEnums.PROVINCE_AGENT.getId());
        } else if (calUtil.isEquals(agAgent.getLevel(), AgentLevelEnums.CITY_AGENT.getId())) {
            bidList = bBusinessMapper.queryBusinessByLocation(agAgent.getCityId(), AgentLevelEnums.CITY_AGENT.getId());
        } else if (calUtil.isEquals(agAgent.getLevel(), AgentLevelEnums.AREA_AGENT.getId())) {
            bidList = bBusinessMapper.queryBusinessByLocation(agAgent.getAreaId(), AgentLevelEnums.AREA_AGENT.getId());
        }
        int totalBusinessOrderNum = 0;
        int todayBusinessOrderNum = 0;

        if (bidList.size() > 0) {
            totalBusinessOrderNum = orderMainMapper.countLocationOrderNumByTypeAndTime(bidList, null);
            //当天区域的订单数
            todayBusinessOrderNum = orderMainMapper.countLocationOrderNumByTypeAndTime(bidList, StaticUtils.DAY_DATA);
        }

        view.addObject("totalBusinessOrderNum", totalBusinessOrderNum);
        view.addObject("todayBusinessOrderNum", todayBusinessOrderNum);
    }

}
